package com.yjhh.chdataservice.component;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by hlantian on 2017/10/9.
 */
@Component
public class ESClientManager {

    private TransportClient client = null;

    public ESClientManager(@Value("${es.cluster.name}") String clusterName,
                           @Value("${es.xpack.security.user}") String xpackSecurityUser,
                           @Value("${es.transporta.address}") String transportAddress) {
        try {
            client = new PreBuiltXPackTransportClient(Settings.builder()
                                                              .put("cluster.name", clusterName)
                                                              .put("xpack.security.user", xpackSecurityUser)
                                                              .build());
            if (transportAddress != null && !"".equals(transportAddress.trim())) {
                String[] transportAddressArray = transportAddress.split(",");
                for (String addr : transportAddressArray) {
                    String[] split = addr.split(":");
                    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(split[0]), Integer.parseInt(split[1])));
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public TransportClient getESClient() {
        return client;
    }

}
